<?php

/**
 *    支付网关通知接口
 *
 *    @author    Garbin
 *    @usage    none
 */
class PaynotifyApp extends MallbaseApp {

    // 构造函数，设置日志路径
    public function __construct()
    {
        ini_set('error_log', ROOT_PATH . '/temp/logs/Paynotify_' . date('y_m_d') . '.log');
    }    

    /**
     *    支付完成后返回的URL，在此只进行提示，不对订单进行任何修改操作,这里不严格验证，不改变订单状态
     *
     *    @author    Garbin
     *    @return    void
     */
    function index() {
        //这里是支付宝，财付通等当订单状态改变时的通知地址
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0; //哪个订单
        if (!$order_id) {
            /* 无效的通知请求 */
            $this->show_warning('forbidden');

            return;
        }

        /* 获取订单信息 */
        $model_order = & m('order');
        $order_info = $model_order->get($order_id);
        if (empty($order_info)) {
            /* 没有该订单 */
            $this->show_warning('forbidden');

            return;
        }

        $model_payment = & m('payment');
        $payment_info = $model_payment->get("payment_code='{$order_info['payment_code']}' AND store_id={$order_info['seller_id']}");
        if (empty($payment_info)) {
            /* 没有指定的支付方式 */
            $this->show_warning('no_such_payment');

            return;
        }

        /* 调用相应的支付方式 */
        $payment = $this->_get_payment($order_info['payment_code'], $payment_info);
        /* 获取验证结果 */
        $notify_result = $payment->verify_return($order_info);
        if ($notify_result === false) {
            /* 支付失败 */
            $this->show_warning($payment->get_error());

            return;
        }

        #TODO 临时在此也改变订单状态为方便调试，实际发布时应把此段去掉，订单状态的改变以notify为准
        //$this->_change_order_status($order_id, $order_info['extension'], $notify_result);

        /* 只有支付时会使用到return_url，所以这里显示的信息是支付成功的提示信息 */
        $this->_curlocal(LANG::get('pay_successed'));
        $this->assign('order', $order_info);
        $this->assign('payment', $payment_info);
        $this->display('paynotify.index.html');
    }

    /**
     * 支付宝异步通知
     */
    function notifyalipay() {

        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayalipay', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($_POST, true);
        error_log('支付宝epayalipay发过来的异步通知为：' . $message);


        //返回验证成功
        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            $this->_change_status($_POST);
            //向接口矩阵提交支付结果
            $this->curl_to_oms($_POST);
        }
        exit;

    }
    function notifyunionpay()
    {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayunionpay', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();
        //返回验证成功
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
        exit;
    }
    /**
     * 微信通知
     */
    function notifyalipaywap() {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayalipaywap', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($notify_result, true);
        error_log('支付宝notifyalipaywap发过来的异步通知为：' . $message);

        //返回验证成功
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
        exit;
    }
    function returnalipaywap()
    {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayalipaywap', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_return();
    }
    /**
     * 微信通知
     */
    function notifywx() {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epaywxnative', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($notify_result, true);
        error_log('微信notifywx发过来的异步通知为：' . $message);

        //返回验证成功
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
        exit;
    }

    function notifywx_wish() {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epaywxnative', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($notify_result, true);
        error_log('正在处理微信支付的心愿单-订金，微信发过来的异步通知为：' . $message);

        // 判断是否支付成功
        if (is_array($notify_result) && array_key_exists('trade_status', $notify_result) && $notify_result['trade_status'] == '1') {
            // 判断订单是否已经创建了，如果没有创建再创建
            // 然后再判断订单是否已经被创建了，如果被创建了，则不再处理
            $mod_pay = &m('wish_pay_log');
            $mod_pay_info = $mod_pay->get('order_sn=' . $notify_result['out_trade_no']);
            if (empty($mod_pay_info)) {
                $this->_addWish($notify_result, 1);
                // 支付成功，给微信成功的响应
                $successXml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';            
                return $successXml;              
            }
        }

        // 否则就是支付失败，给微信的失败响应
        $failXml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';          
        return $failXml;        
    }

    function notifywx_finish_wish() {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epaywxnative', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($notify_result, true);
        error_log('正在处理微信支付的心愿单-尾款，微信发过来的异步通知为：' . $message);

        //返回验证成功
        if ($notify_result['trade_status']) {
//            $this->_change_status($notify_result);
            $this->_addFinishWish($notify_result,1);
        }
        exit;
    }

    function notifyalipay_wish() {
        $payment = $this->_get_payment('epayalipay', array());
        $notify_result = $payment->verify_notify();

        // 开始记录日志
        $message = print_r($_POST, true);
        error_log('正在处理支付宝支付的心愿单-订金，该订单$_POST详情信息为：' . $message);

        // 只判断TRADE_SUCCESS即可，如果是TRADE_FINISHED则不处理
        if (!empty($_POST) && $_POST['trade_status'] == 'TRADE_SUCCESS') {
            // 说明支付成功
            // 然后再判断订单是否已经被创建了，如果被创建了，则不再处理
            $mod_pay = &m('wish_pay_log');
            $mod_pay_info = $mod_pay->get('order_sn=' . $_POST['out_trade_no']);
            if (empty($mod_pay_info)) {
                $this->_addWish($_POST,2);
            }
//            $this->curl_to_oms($_POST);
            echo 'success';
            exit();
        } else {
           /* 支付失败 */
           echo 'fail';
           exit;
        }

        // if ($payment === false) {
        //    /* 支付失败 */
        //     echo 'fail';
        //     exit;
        // }else{
        //     $this->_addWish($_POST,2);
        //     echo 'success';
        //     exit;
        // }

    }

    function notifyalipay_finish_wish() {

        $payment = $this->_get_payment('epayalipay', array());
        $payment->verify_notify();

        // 开始记录日志
        $message = print_r($_POST, true);
        error_log('正在处理支付宝支付的心愿单-尾款，该订单详情信息为：' . $message);
        $message = print_r($payment, true);
        error_log('同时支付宝发过来的异步通知为：' . $message);

        if ($payment === false) {
//            /* 支付失败 */
            echo 'fail';
            exit;
        }else{
            $this->_addFinishWish($_POST,2);
//            $this->curl_to_oms($_POST);
            echo 'success';            
            exit;
        }
    }
    
    function returnwx(){
        $result = 0;
        $order_sn = $_GET['order_sn'];
        if(empty($order_sn)){
            echo $result;
            return ;
        }
        $account_log_mod = & m('account_log');
        $account_log = $account_log_mod->get("order_sn='$order_sn'");
        //如果充值成功
        if($account_log['complete'] == '1'){
            $result = '1';//表示为充值 到充值界面
            //如果是商品订单
            $mod_order = & m('order');
            $order_info = $mod_order->get('order_sn=' . $order_sn);
            if ($order_info) {
                $result = '2'; //表示为订单购买 到订单页面
            }
        }
        echo $result;
    }

    /*网银在线手机支付异步通知*/
    function notifyjdpaywap()
    {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayjdpaywap', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();
        //返回验证成功
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
        exit;
    }
    /*网银在线手机支付同步通知*/
    function returnjdpaywap()
    {
        $token = trim($_GET['token']);
        if ($token&&$this->visitor->get('user_id')) {
            $member_mod = &m('member');
            $member = $member_mod->edit('user_id=' . $this->visitor->get('user_id'),array('jdpaywap_token'=>$token));
        }
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayjdpaywap', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_return();
    }
    /*网银在线支付异步通知*/
    function notifyjdpay()
    {
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayjdpay', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_notify();
        //返回验证成功
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
        exit;
    }
    /*网银在线手机支付同步通知*/
    function returnjdpay()
    {
        $token = trim($_GET['token']);
        if ($token&&$this->visitor->get('user_id')) {
            $member_mod = &m('member');
            $member = $member_mod->edit('user_id=' . $this->visitor->get('user_id'),array('jdpay_token'=>$token));
        }
        /* 调用相应的支付方式 */
        $payment = $this->_get_payment('epayjdpay', array());
        /* 获取验证结果 */
        $notify_result = $payment->verify_return();
    }
    
    /**
     * out_trade_no 商户订单号
     * trade_no 交易凭据单号
     * total_fee 涉及金额
     * trade_status 状态 为1 验证成功  为0 验证失败
     */
    function _change_status($notify_result) {
//        extract($notify_result);
//        if(empty($out_trade_no)||empty($total_fee)||empty($total_fee)){
//            return;
//        }
        $out_trade_no = $notify_result['out_trade_no'];
        if($notify_result['total_amount']){
            $total_fee = $notify_result['total_amount'];
        }else if($notify_result['total_fee']){
            $total_fee = $notify_result['total_fee'];
        }
        $time = gmtime();
        $member_mod = & m('member');
        $account_log_mod = & m('account_log');
        //根据用户订单号，获取充值者的ID
        $account_log = $account_log_mod->get("money_flow = 'income' AND order_sn='$out_trade_no' AND money=".$total_fee." AND type=".ACCOUNT_TYPE_CZ);
        if (empty($account_log) || $account_log['complete'] == '1') {
            return;
        }

        $user_id = $account_log['user_id'];
        //获取用户的余额
        $member_mod->db->query('start transaction');
   
        $row_member = $member_mod->getAll('SELECT * FROM '.$member_mod->table.' WHERE user_id='.$user_id.' FOR UPDATE');
        if(!is_array($row_member) || empty($row_member)){//不存在，则结束
            //修改记录
            $edit_account_log = array(
                'add_time' => $time,
                'money' => 0,
                'complete' => 1,
                'states' => 61,
                'log_text'=>'用户不存在，其充值的'.$total_fee.'元存在平台账户中',
            );
            $account_log_mod->edit('order_sn=' . '"' . $out_trade_no . '"', $edit_account_log);
            $member_mod->db->query('rollback');
            return;
        }
        $row_member= current($row_member);
        //计算新的余额
        $old_money = $row_member['money'];
        $new_money = $old_money + $total_fee;
        $edit_money = array(
            'money' => $new_money,
        );

        $mysql_flag=$member_mod->edit('user_id=' . $user_id, $edit_money);
        if(!$mysql_flag){
                $member_mod->db->query('rollback');
                $ms=& ms();
                $ms->pm->send(MSG_SYSTEM, $user_id, '', '系统繁忙，订单号为'.$out_trade_no.'自动充值失败，请联系管理员手工为您的账户充值'.$total_fee.'元');
                return;
            }
        //修改记录
        $edit_account_log = array(
            'add_time' => $time,
            'money' => $total_fee,
            'complete' => 1,
            'states' => 61,
        );
        $mysql_flag=$account_log_mod->edit('order_sn=' . '"' . $out_trade_no . '"', $edit_account_log);
            if(!$mysql_flag){
                $member_mod->db->query('rollback');
                $ms=& ms();
                $ms->pm->send(MSG_SYSTEM, $user_id, '', '系统繁忙，订单号为'.$out_trade_no.'自动充值失败，请联系管理员手工为您的账户充值'.$total_fee.'元');
                return;
            }else{
                $member_mod->db->query('commit');
            }
        $order_id_array=array();
        if(!empty($account_log['orders_group'])){
            $order_id_array= explode(',', $account_log['orders_group']);
        }else{
            $account_log['order_id'] && $order_id_array=array($account_log['order_id']);
        }
        //---------------------  以下是判断  是否启用 自动付款----------------------

        $mod_order = & m('order');
      
            foreach($order_id_array as $order_id){
        //根据用户返回的 order_sn 判断是否为订单
        $order_info = $mod_order->get('order_id=' . $order_id);

        if (!empty($order_info)) {
            if(!$seller_info=$member_mod->get($order_info['seller_id'])){
                continue;
            }
            //如果存在订单号  则自动付款
$member_mod->db->query('start transaction');
            //买家扣除金额
            $buyer_data = array(
                'user_id' => $order_info['buyer_id'],
                'user_name' => $order_info['buyer_name'],
                'order_id' => $order_id,
                'order_sn ' => $order_info['order_sn'],
                'add_time' => $time,
                'type' => ACCOUNT_TYPE_BUY,
                'money_flow' => 'outlay',
                'money' => $order_info['order_amount'],
                'log_text' => '购买商品店铺:' . $order_info['seller_name'],
            );
           $mysql_flag=$member_mod->change_money($buyer_data);
            if(!$mysql_flag){
                $member_mod->db->query('rollback');
                continue;
            }
            //卖家对资金进行操作，新增记录同时把金额加入冻结资金
            $seller_data = array(
                'user_id' => $order_info['seller_id'],
                'user_name' => '',
                'order_id' => $order_id,
                'order_sn ' => $order_info['order_sn'],
                'add_time' => $time,
                'type' => ACCOUNT_TYPE_SELLER,
                'money_flow' => 'income',
                'money' => $order_info['order_amount'],
                'log_text' => '出售商品买家:'.$order_info['buyer_name'],
            );
            $mysql_flag=$member_mod->change_money($seller_data,'money_dj');
            if(!$mysql_flag){
                $member_mod->db->query('rollback');
                continue;
            }
            //更新定单状态
            $order_edit_array = array(
                'status' => 20, //20就是 待发货了
				'pay_time'=>gmtime(),
//                lichen 2019/5/23 start
                'out_trade_sn' => $notify_result['trade_no']
//                lichen 2019/5/23 end

            );
            $mysql_flag=$mod_order->edit($order_id, $order_edit_array);
            if(!$mysql_flag){
                $member_mod->db->query('rollback');
                continue;
            }else{
                $member_mod->db->query('commit');
            }
            
            /* 发送邮件给卖家，提醒付款成功 */
            $mail = get_mail('toseller_online_pay_success_notify', array('order' => $order_info));
            $this->_mailto($seller_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
            /* 同步发送 */
            $this->_sendmail(true);
        }
        }
    }

    /**
     *    改变订单状态
     *
     *    @author    Garbin
     *    @param     int $order_id
     *    @param     string $order_type
     *    @param     array  $notify_result
     *    @return    void
     */
    function _change_order_status($order_id, $order_type, $notify_result) {
        /* 将验证结果传递给订单类型处理 */
        $order_type = & ot($order_type);
        $order_type->respond_notify($order_id, $notify_result);    //响应通知
    }

    function _addWish($notify_result,$pay_type){
        $order_sn = $notify_result['out_trade_no'];
        $mod_temp = & m('wish_temp');
        $mod_wish = & m('wish');
        $mod_pay = & m('wish_pay_log');
        $temp_info = $mod_temp->get('order_sn=' . $order_sn);
        $data = array(
            'user_id' => $temp_info['user_id'],
            'goods_id' => $temp_info['goods_id'],
            'spec_id' => $temp_info['spec_id'],
            'addr_id' => $temp_info['addr_id'],
            'num' => $temp_info['num'],
            'add_time' => time(),
            'goods_price' => $temp_info['goods_price']
//            'finish_time' => time()+60*24*3600,
        );
        $res = $mod_wish->add($data);
        // 开始记录日志
        if(!$res){
            $message = print_r($data, true);
            error_log('心愿单记录为：' . $message);
        }
        $data_pay = array(
            'wish_id' => $res,
            'user_id' => $temp_info['user_id'],
            'money' => WISH_PRICE,
            'type' => 1,
            'order_sn' => $order_sn,
            'remark' => '我创建了一个心愿单',
            'trade_no' => $notify_result['trade_no'],
            'pay_type' => $pay_type,
            'create_time' => time(),
        );
        $res_pay = $mod_pay->add($data_pay);
        if(!$res_pay){
            $message = print_r($data_pay, true);
            error_log('心愿单支付记录为：' . $message);
        }

    }

    function _addFinishWish($notify_result,$pay_type){
        $order_sn = $notify_result['out_trade_no'];
        $mod_temp = & m('wish_temp');
        $mod_wish = & m('wish');
        $mod_log = & m('wish_log');
        $mod_pay = & m('wish_pay_log');
        $mod_spec = & m('goodsspec');
        $mod_goods = & m('goods');
        $mod_member = & m('member');
        $mod_address = & m('address');
        $mod_order = & m('order');
        $mod_order_goods = & m('ordergoods');
        $mod_order_extm = & m('orderextm');
//        $mod_order_log = & m('order_log');
        $temp_info = $mod_temp->get('order_sn2=' . $order_sn);
        //获取心愿单id
        $res_pay_first = $mod_pay->get('order_sn=' . $temp_info['order_sn']);
//        $res_wish = $mod_wish->get('id='.$res_pay_first['wish_id']);
        $res_spec = $mod_spec->get('spec_id='.$temp_info['spec_id']);
        $res_goods = $mod_goods->get('goods_id='.$res_spec['goods_id']);
        $res_log_count = $mod_log -> find(array('conditions'=>'wish_id='.$res_pay_first['wish_id']));
        $data_pay = array(
            'wish_id' => $res_pay_first['wish_id'],
            'user_id' => $temp_info['user_id'],
            'money' => $temp_info['goods_price'] - (count($res_log_count))*30 - WISH_PRICE,
            'type' => 2,
            'order_sn' => $order_sn,
            'remark' => '我完成了一个心愿单',
            'trade_no' => $notify_result['trade_no'],
            'pay_type' => $pay_type,
            'create_time' => time(),
        );
        // 开始记录日志
        $message = print_r($res_log_count, true);
        error_log('帮砍信息为：' . $message);
        $message = print_r(WISH_PRICE, true);
        error_log('心愿单金额为：' . $message);
        $message = print_r($data_pay, true);
        error_log('支付信息为：' . $message);
        $res_pay = M('wish_pay_log')->add($data_pay);
        $res_member = $mod_member->get(array('conditions'=>'user_id='.$temp_info['user_id']));
        $res_address = $mod_address->get('addr_id='.$temp_info['addr_id']);
        if($pay_type == 1){
            $payment_name = '手机微信支付';
            $payment_code = 'wxpay_app';
        }else if($pay_type == 2){
            $payment_name = '手机支付宝支付';
            $payment_code = 'alipay_app';
        }
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        //减库存
        $data_spec = array(
            'stock' => (int)$res_spec['stock'] - 1
        );
        $res_spec_save = $mod_spec->edit($res_spec['spec_id'],$data_spec);



    

        //生成订单
        $data_order = array(
            'order_sn' => $order_sn,
            'type' => 'wishOrder',
            'extension' => 'normal',
            'seller_id' => 2,
            'seller_name' => 'Cloud-Moda',
            'buyer_no' => $res_member['user_no'],
            'phone_mob' => $res_member['phone_mob'],
            'buyer_name' => $res_member['buyer_name'],
            'buyer_id' => $temp_info['user_id'],
            'buyer_email' => $res_member['email'],
            'status' => 20,
            'add_time' => time(),
            'payment_name' => $payment_name,
            'payment_code' => $payment_code,
            'out_trade_sn' => $notify_result['trade_no'],
            'pay_time' => time(),
            'goods_amount' => $temp_info['goods_price'],
            'order_amount' => $mod_pay->getPayLog($res_pay_first['wish_id'],1) + $mod_pay->getPayLog($res_pay_first['wish_id'],2),
        );
        $res_order = $mod_order->add($data_order);
        $data_order_goods = array(
            'order_id' =>  $res_order,
            'goods_id' => $res_spec['goods_id'],
            'goods_name' => $res_goods['goods_name'],
            'spec_id' => $res_spec['spec_id'],
            'specification' => $res_goods['spec_name_1'].':'.$res_spec['spec_1value'].' '.$res_goods['spec_name_2'].':'.$res_spec['spec_2'].' '.$res_goods['spec_name_3'].':'.$res_spec['spec_3'],
            'price' => $mod_pay->getPayLog($res_pay_first['wish_id'],1) + $mod_pay->getPayLog($res_pay_first['wish_id'],2),
            'price_amount' => $mod_pay->getPayLog($res_pay_first['wish_id'],1) + $mod_pay->getPayLog($res_pay_first['wish_id'],2),
            'quantity' => 1,
            'price_total' => $mod_pay->getPayLog($res_pay_first['wish_id'],1) + $mod_pay->getPayLog($res_pay_first['wish_id'],2),
            'goods_image'=>$res_spec['spec_1'],
            'goods_old_price'=> $temp_info['goods_price'],

        );
        $order_goods = $mod_order_goods -> add($data_order_goods);
        $data_order_goods = array(
            'order_id' => $res_order,
            'consignee' => $res_address['consignee'],
            'region_id' => $res_address['region_id'],
            'region_name' => $res_address['region_name'],
            'user_no' => $res_address['user_no'],
            'address' => $res_address['address'],
            'phone_mob' => $res_address['phone_mob'],
            'shipping_name' => '商家包邮'
        );
        $res_order_extm = $mod_order_extm -> add($data_order_goods);
//        $data_order_log = array(
//            'order_id' => $res_order['order_id'],
//            'operator' => $res_member['user_name'],
//            'changed_status' => '下订单',
//            'remark' => '买家完成心愿单',
//            'log_time' => time(),
//            'order_log_status' => 1,
//            'operator_type' => 'buyer'
//        );

//        $res_order_log = $mod_order_log -> add($data_order_log);
        $data_wish = array(
            'finish_time' => time(),
            'order_id' => $res_order,
            'state' => 2
        );
        $res_wish = $mod_wish -> edit($res_pay_first['wish_id'],$data_wish);


    }

    function curl_to_oms($data){
        $payExchangeInfoHead=array();
        $payInfoHead=array(
            'initalResponse'=>json_encode($data),//结果原文
            'payTransactionId'=>$data["trade_no"],//支付单号
            'tradingTime'=>date('YmdHis',strtotime($data["gmt_payment"])),//交易时间
        );
        array_push($payExchangeInfoHead,array(
            'initalResponse'=>json_encode($data),
            'payTransactionId'=>$data["trade_no"],
            'tradingTime'=>date('YmdHis',strtotime($data["gmt_payment"])),
        ));
        $payExchangeInfoLists=array();
        array_push($payExchangeInfoLists,array(
            'orderNo'=>$data["out_trade_no"],//电商交易单号
        ));
        $is_ok="1";
        if($data["trade_status"]=='TRADE_SUCCESS')
        {
            $is_ok="1";
        }
        else
        {
            $is_ok="0";
        }
        $payExInfo=array(
            'payment_type'=>'支付宝(中国)网络技术有限公司',
            'is_success'=>$is_ok,//交易状态
            'payExchangeInfoHead'=>$payExchangeInfoHead,
            'payExchangeInfoLists'=>$payExchangeInfoLists,
        );
        $str1=json_encode($payExInfo);
        $this->curl_post($str1);//提交请求
    }

    //post请求方法
    function curl_post($str)
    {
        //$data=array('Result'=>$str);
        $curl = curl_init('https://api.jingjing.shop/api/pay/payreal');
        //$curl = curl_init('http://161h2715w4.imwork.net:16658/api/paytest/rcvpay');
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$str);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            )
        );
        curl_exec($curl);
        curl_close($curl);
    }

    function _get_oms_data($data = array()){
        $return_array['OrderItets'] = array();
        foreach ($data['order_goods'] as $k => $v) {
            if(!array_key_exists($data['order_goods'][$k]['goods']['goods_id'],$return_array['OrderItets'])){
//                if(!array_search($data[$k]['spec'],$return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'],true)){
//                    if(!isset($return_array[$v['goods_id']]['OrderItemDetails'])){
//                        $return_array[$v['goods_id']]['OrderItemDetails'] = array();
//                    }
//                $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'] = array();
                $return_array['OrderItets'][$v['goods_id']]['ProductId'] = $data['order_goods'][$k]['goods']['goods_id'];
                $return_array['OrderItets'][$v['goods_id']]['ItemName'] = '爱莎';
                $return_array['OrderItets'][$v['goods_id']]['Unit'] = $data['order_goods'][$k]['unit']['unit_code'];
                $return_array['OrderItets'][$v['goods_id']]['Currency'] = '142';
                $return_array['OrderItets'][$v['goods_id']]['CiqCurrency'] = '156';
                $return_array['OrderItets'][$v['goods_id']]['Country'] = $data['order_goods'][$k]['country']['country_code'];
                $return_array['OrderItets'][$v['goods_id']]['CiqCountry'] = $data['order_goods'][$k]['country']['ciq_code'];
                $return_array['OrderItets'][$v['goods_id']]['WrapTypeCode'] = $data['order_goods'][$k]['wrap']['wrap_code'];
                //                test
                $return_array['OrderItets'][$v['goods_id']]['PurposeCode'] = '9';
                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = $data['seller_id'];
                $return_array['OrderItets'][$v['goods_id']]['StoreId'] = $data['seller_id'];
//                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = 16;

                $return_array['OrderItets'][$v['goods_id']]['ShelfGoodsName'] = $data['brand'];

                $return_array['OrderItets'][$v['goods_id']]['ProductSku'] = 'none';
                $return_array['OrderItets'][$v['goods_id']]['BarCode'] = 'none';


            }
            $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'][] = array(
                'AttributeSku' => $data['order_goods'][$k]['spec']['sku'],
                'Quantity' => $data['order_goods'][$k]['quantity'],
                'Price' => $data['order_goods'][$k]['spec']['price'],
                'TaxRates' => $data['order_goods'][$k]['tax']['consolidated_tax'],
                'OrderTax' => $data['order_goods'][$k]['tax_price'],
                'OrderDiscount' => 0,
                'BarCode' => $data['order_goods'][$k]['spec']['barcode'],
                'TradeType' => $data['order_goods'][$k]['storestock']['stock_style'],
                'PriceInclTax' => $data['order_goods'][$k]['goods']['price'],
                'TotalPrice' => $data['order_goods'][$k]['price_total'],
//                test
                'CustomsChannelId' =>  $data['order_goods'][$k]['storestock']['stock_id'],
//                'CustomsChannelId' =>  12,
            );
//                    $return_array[$v['goods_id']][''] = array()
//                array_push($return_array[$v['']]['OrderItemDetails'][''],);
//            }else{
//                $return_array['OrderItets'][$v['goods_id']] = array();

//            }
        }
        $address_str = $this->emptyreplace($data['order_extm']['region_name']);
        $address_str = $address_str . $data['order_extm']['address'];
        $return_array['OrderStatusId'] = 10;
        $return_array['ShippingStatusId'] = 20;
        $return_array['PaymentStatusId'] = 10;
        $return_array['PaymentMethodSystemName'] = 'none';
        $return_array['ShippingMethod'] = 'ground';
        $return_array['CustomerCurrencyCode'] = '142';
        $return_array['AuthorizationTransactionResult'] = 'none';
        $return_array['OrderTotal'] = $data['goods_amount'];
        $return_array['AffiliateId'] = 0;
        $return_array['RefundedAmount'] = 0;
        $return_array['CreatedOnUtc'] = date("Y-m-d H:i:s");
        $return_array['OrderNo'] = $data['order_sn'];
        $return_array['BuyerName'] = $this->visitor->get('real_name');
        $return_array['BuyerTelephone'] = $data['phone_mob'];
        $return_array['BuyerRegNo'] = $data['phone_mob'];
        $return_array['BuyerIdType'] = 1;
        $return_array['BuyerIdNumber'] = $this->visitor->get('user_no');
        $return_array['PayCode'] = 'none';
        $return_array['PayName'] = 'none';
        $return_array['PayTransactionId'] = 'none';
        $return_array['Consignee'] = $data['order_extm']['consignee'];
        $return_array['ConsigneeTelephone'] = $data['order_extm']['phone_mob'];
        $return_array['ConsigneeAddress'] = $address_str;
        $return_array['IdCard'] = $data['order_extm']['user_no'];
        $return_array['IdType'] = 1;
        $return_array['EtradeCountryCode'] = '156';
        $return_array['OrderItems'] = array();
        $return_array['OrderItems'] = array_values($return_array['OrderItets']);
        return $return_array;

    }

    function _get_pay_data($order_sn,$data){
        $return_array = array();
        foreach ($data as $k => $v){
            $return_array[] = array(
                'PayName' => $v['pay_type'] == 1 ? '财付通支付科技有限公司' : '支付宝(中国)网络技术有限公司',
                'OrderNo' => $order_sn,
    		    'WishNo' => $v['order_sn'],
    		    'PayTransactionId' => $v['trade_no'],
    		    'PayPrice' => $v['money'],
    		    'PayTime' => gmtime(DATE_ATOM,$v['create_time'])
            );
        }
    }

    function _post_to_oms($url,$port=80,$t=30,$method='get',$data=null)
    {
        $info=parse_url($url);
        $fp = fsockopen('ssl://'.$info['host'],$port,$errno,$errstr,$t);
        // 判断是否有数据
        if(isset($data) && !empty($data))
        {
            $query = http_build_query($data); // 数组转url 字符串形式
        }else
        {
            $query=null;
        }
        // 如果用户的$url "http://www.manongjc.com/";  缺少 最后的反斜杠
        if(!isset($info['path']) || empty($info['path']))
        {
            $info['path']="/index.html";
        }
        // 判断 请求方式
        if($method=='post')
        {
            $head = "POST ".$info['path']." HTTP/1.0".PHP_EOL;
        }else
        {-
            $head = "GET ".$info['path']."?".$query." HTTP/1.0".PHP_EOL;
        }

        $head .= "Host: ".$info['host'].PHP_EOL; // 请求主机地址
        $head .= "Referer: https://".$info['host'].':'.$port.$info['path'].PHP_EOL;
        if(isset($data) && !empty($data) && ($method=='post'))
        {
            $head .= "Content-type: application/x-www-form-urlencoded".PHP_EOL;
            $head .= "Content-Length: ".strlen(trim($query)).PHP_EOL;
            $head .= PHP_EOL;
            $head .= trim($query);
        }else
        {
            $head .= PHP_EOL;
        }
//        var_dump($head);exit;
        $write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
        while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }
    }

    function emptyreplace($str)
    {
        $str = preg_replace('/\s+/',',',$str);
        return $str;
    }

}

?>
